package com.czxy.service;

import com.czxy.mapper.NewsMapper;
import com.czxy.pojo.News;
import com.czxy.vo.PageRequest;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author 张青卯
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class NewsService {

    private final NewsMapper newsMapper;

    @Autowired
    public NewsService(NewsMapper newsMapper) {
        this.newsMapper = newsMapper;
    }

    public List<News> findNewsByPage(PageRequest pageRequest){
        PageHelper.startPage(pageRequest.getPage(),pageRequest.getPerPage());
        Example example = new Example(News.class);
        Example.Criteria criteria = example.createCriteria();
        if(StringUtils.isBlank(pageRequest.getSortWay()) || pageRequest.getSortWay().equals("desc")){
            example.setOrderByClause("created_at desc");
        }else{
            example.setOrderByClause("created_at asc");
        }
        List<News> list = newsMapper.selectByExample(example);
        return list;
    }

    public int findTotalCount(){
        return newsMapper.selectAll().size();
    }
}
